package com.zhiban.project.controller;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
import org.zefer.pd4ml.PD4PageMark;

import dinamica.GenericOutput;
import dinamica.GenericTransaction;
import dinamica.Recordset;
import dinamica.xml.Document;

public class DownloadPdf extends GenericOutput {

	String fpath = null;
	
	private String fname;
	private  String created;

	public DownloadPdf() {
	}

	public static String getAppURL(HttpServletRequest request) {
		if (request == null)
			return "";

		StringBuffer url = new StringBuffer();
		int port = request.getServerPort();
		if (port < 0) {
			port = 80; // Work around java.net.URL bug
		}
		String scheme = request.getScheme();
		url.append(scheme);
		url.append("://");
		url.append(request.getServerName());
		if ((scheme.equals("http") && (port != 80))
				|| (scheme.equals("https") && (port != 443))) {
			url.append(':');
			url.append(port);
		}
		url.append(request.getContextPath());
		return url.toString();
	}

	public static String getContentFromIn(HttpURLConnection urlConn,
			String charset) {
		BufferedReader br = null;
		StringBuilder content = new StringBuilder(200);
		InputStream in = null;
		try {
			if (null == urlConn) {
				return "";
			}
			if (null == in) {
				in = urlConn.getInputStream();
			}
			if (null != in) {
				br = new BufferedReader(new InputStreamReader(in, charset));
				String line = "";
				while ((line = br.readLine()) != null) {
					content.append(line);
				}
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
		}
		return content.toString();
	}

	public static String replaceTag(String str, List<String> list) {
		String regxp = "<\\s*(input|textarea)\\s*([^>]*)\\s*>";
		Pattern pattern = Pattern.compile(regxp);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		int index = 0;
		while (result1) {
			String replaceStr = "&nbsp;";
			if (list.size() > index) {
				replaceStr = list.get(index);
			}
			if (replaceStr == null) {
				replaceStr = "&nbsp;";
			}
			matcher.appendReplacement(sb, replaceStr);
			result1 = matcher.find();
			index++;
		}
		matcher.appendTail(sb);
		String contentString = sb.toString().replaceAll("</textarea>", "");
		int captionIndex = contentString.indexOf("<caption>");
		int ecaptionIndex = contentString.indexOf("</caption>");
		StringBuilder builder = new StringBuilder();
		if (captionIndex > -1) {
			String ttitle = contentString.substring(
					captionIndex + "<caption>".length(), ecaptionIndex);
			String ttitle2 = contentString.substring(captionIndex,
					ecaptionIndex + "</caption>".length());
			ttitle = ttitle.replace("<strong>", "");
			ttitle = ttitle.replace("</strong>", "");
			int tableindex = contentString.indexOf("<table");
			String starString = contentString.substring(0, tableindex);
			builder.append(starString);
			builder.append("<div style=\"text-align:center\">" + ttitle
					+ "</div>");
			String tableString = contentString.substring(tableindex,
					contentString.length());
			tableString = tableString.replaceAll("width:(\\d+)px",
					"width:630px");
			builder.append(tableString);

			builder = new StringBuilder(builder.toString().replace(ttitle2, ""));
		} else {
			builder.append(sb);
		}
		return builder.toString();
	}

	private String getPath(GenericTransaction data, Document doc)
			throws Throwable {
		String file_recordset = doc.getElement("file-recordset").getValue();
		Recordset rsFile = data.getRecordset(file_recordset);
		rsFile.first();
		String filePath = rsFile.getString("path");
		fname=rsFile.getString("fname");
		created=rsFile.getString("created");
		
		return filePath;
	}
	

	private String getContent(File srcFile) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(new FileInputStream(srcFile), "utf-8"));
		String valueString = null;
		StringBuilder builder = new StringBuilder();
		while ((valueString = bufferedReader.readLine()) != null) {
			builder.append(valueString);
		}
		bufferedReader.close();
		return builder.toString();
	}

	private List<String> getItem(GenericTransaction data, Document doc)
			throws Throwable {
		List<String> stringList = new ArrayList<String>();
		String file_recordset = doc.getElement("item-recordset").getValue();
		Recordset rsFile = data.getRecordset(file_recordset);
		HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
		Integer maxNumber = 0;
		while (rsFile.next()) {
			String item_code = rsFile.getString("item_code");
			Integer number = Integer.parseInt(item_code.replace("code", ""));
			String item_value = rsFile.getString("item_value");
			hashMap.put(number, item_value);
			if (maxNumber < number) {
				maxNumber = number;
			}
		}
		for (int i = 1; i <= maxNumber; i++) {
			if (hashMap.get(i) == null) {
				stringList.add("&nbsp;");
			} else {
				stringList.add(hashMap.get(i));
			}
		}
		return stringList;
	}

	public void print(GenericTransaction data) throws Throwable {
		Document doc = getConfig().getDocument();
		try {
			String tuid = this.getRequest().getParameter("tuid");
			fpath = this.getRequest().getRealPath("/") + File.separator
					+ "pdffile";
			String templatepath = this.getRequest().getRealPath("/")
					+ File.separator + "template";
			File templateFile = new File(templatepath, getPath(data, doc));
			String content = getContent(templateFile);
			List<String> list = getItem(data, doc);
			content = replaceTag(content, list);
			StringBuilder builder = new StringBuilder();
			builder.append("<style>html,body{height:100%}.container-fluid{height:100%}.title{font-size:20px;font-weight:bold;text-align:center;margin-top:20px}.ctable{margin-top:20px}.ctable .head{text-align:center}.ctable input{border:medium none;width:100%}.ctable textarea{border:medium none;box-shadow:none}.ctable textarea:focus{border:medium none;box-shadow:none}.ctable td{padding:5px}.ctable td.center{text-align:center}button.btnstyle2{background:#28a1b2;color:#fff;border:1px solid #0b2c77;width:80px;height:30px;line-height:10px;padding:0;border-radius:0}button.btnstyle2:active{background:#29a1b1;color:#fff}button.btnstyle2:hover{background:#29a1b1;color:#fff}.buttonclass .btnstyle{display:none}table input{border:medium none;width:100%}table textarea{border:medium none;box-shadow:none};.downwei{text-align:right}</style>");
			content=content.replaceAll("</body>", "<div class=downwei>维护人:"+fname+" 维护时间:"+created+"</div></body>");
			builder.append(content);
			
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			generatePDF_2(outputStream, builder.toString(),
					"VRB-52D型多普勒全向信标年维护记录表");

			getResponse().setContentType("application/pdf");
			getResponse().setHeader("Content-Disposition",
					getAttachmentString(tuid + ".pdf"));
			ServletOutputStream out = getResponse().getOutputStream();
			out.write(outputStream.toByteArray());
			outputStream.close();
		} catch (Throwable e) {
			throw new Throwable("操作失败", e);
		}
	}

	// HTML代码来自于HTML文件
	public void generatePDF_2(ByteArrayOutputStream outputStream,
			String contents, String title) throws Exception {
		PD4ML pd4ml = new PD4ML();
		PD4PageMark headerMark = new PD4PageMark();
		headerMark.setAreaHeight(30);
		headerMark.setInitialPageNumber(1);
		headerMark.setPagesToSkip(1);
		headerMark.setTitleAlignment(PD4PageMark.CENTER_ALIGN);
		headerMark.setHtmlTemplate(title);
		pd4ml.setPageHeader(headerMark);
		PD4PageMark footerMark = new PD4PageMark();
		footerMark.setAreaHeight(30);
		footerMark.setInitialPageNumber(10);
		footerMark.setHtmlTemplate("武汉大学");
		// pd4ml.setPageFooter(footerMark);
		pd4ml.setPageSize(PD4Constants.A4);
		pd4ml.useTTF(fpath + "\\fonts", true);
		pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312");
		pd4ml.render(new StringReader(contents), outputStream);
	}

	protected String getAttachmentString(String excelFileName) {
		String filename = excelFileName;
		try {
			if (getRequest().getHeader("user-agent").indexOf("MSIE") != -1) {
				filename = URLEncoder.encode(filename, "utf-8");
				filename = filename.replaceAll("\\+", "%20");
			} else {
				filename = new String(filename.getBytes("utf-8"), "iso-8859-1");
			}
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return (new StringBuilder("attachment; filename=\"")).append(filename)
				.append("\";").toString();
	}
}